<?php
/**
 * @author qingyu8@staff.weibo.com
 * @date 2018/02/03
 */

namespace api\modules\v1\actions;

use Yii;
use yii\base\Model;
use yii\db\ActiveRecord;
use yii\web\NotFoundHttpException;
use yii\web\ServerErrorHttpException;
use yii\rest\Action;

class LoginAction extends Action {
    public function run() {
        /* @var $model ActiveRecord */
        try {
            $username = Yii::$app->request->post('username');
            $model = $this->findModel($username);
        } catch (NotFoundHttpException $e) {
            return [
                'code' => 404,
                'msg' => '用户不存在'
            ];
        }

        if ($this->checkAccess) {
            call_user_func($this->checkAccess, $this->id, $model);
        }

        $model->scenario = ($this->modelClass)::SCENARIO_LOGIN;
        $model->load(Yii::$app->getRequest()->getBodyParams(), '');
        if ($model->save() === false) {
            if ($model->hasErrors()) {
                $attr = key($model->getFirstErrors());
                return [
                    'code' => 404,
                    'msg' => current($model->getFirstErrors())
                ];
            } else {
                throw new ServerErrorHttpException('Failed to update the object for unknown reason.');
            }
        }
        //return ['debug'=>'hello'];

        return $model;
    }
}